﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine;
public class DragObjectX : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
    public float maxX;
    public float minX;
    private float posX;
    public bool isDrag = false;
    public float dragStartPosX;
    public VoidEvent startDragEvent;
    public VoidEvent endDragEvent;

    public RectTransform target;

    RectTransform cacheTarget
    {
        get
        {
            if (target == null)
            {
                target = GetComponent<RectTransform>();
            }
            return target;
        }
    }


    public void OnDrag(PointerEventData eventData)
    {
        posX = eventData.position.x;
        Debug.Log("posY : " + eventData.position.x);
        if (posX < minX)
        {
            //OnStartDragEvent();
            posX = minX;
        }
        else if (posX > maxX)
        {
            //OnStartDragEvent();
            posX = maxX;
        }
        target.position = new Vector3(posX, target.position.y,  target.position.z);
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        isDrag = true;
        OnStartDragEvent();
        dragStartPosX = target.position.x;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        isDrag = false;
        if (null != endDragEvent)
            endDragEvent.Invoke();
    }

    private void OnStartDragEvent()
    {
        if (null != startDragEvent)
            startDragEvent.Invoke();
    }


}
